package b3.model
{
	import b3.config.*;
	import b3.net.ServerEvent;
	import b3.net.ServerRequest;
	import b3.scene.home.grid.*;
	
	import flash.geom.Point;
	import flash.utils.*;
	
	public class BuildingModel extends Model
	{
		public var id:int;
		//索引
		public var buildingIndex:int;
		//建筑类型
		public var buildingType:int;
		//高度
		public var height:int;
		//人口数（当前）
		public var population:int;
		//人口数（最大值）
		public var historyMaxPopulation:int;
		//顶样式
		public var roofType:int;
		//街区索引
		public var sectionIndex:int;
		//位置X
		public var posX:int;
		//位置Y
		public var posY:int;
		//所有者（所在town的玩家ID）
		public var ownerId:int;
		//占有者（当前占有的玩家ID）
		public var occupantId:int;
		//占地X
		public var isoWidth:int;
		//占地Y
		public var isoHeight:int;
		//收租时间（秒）
		public var rentCollectTime:int;
		//当前被偷的次数
		public var stealRentCount:int;
		//上次点击收租时间（秒）
		private var lastRentClickTime:int;
		//社交信息
		public var socialInfos:Array;
		public var socialMessageRead:Boolean;
		//是否已经放入城市
		public var locatedFlag:Boolean;
		
		public function BuildingModel()
		{
			roofType = -1;
			locatedFlag = true;
		}
		
		public function copy():BuildingModel
		{
			var buildingModel:BuildingModel = new BuildingModel();
			buildingModel.id = this.id;
			buildingModel.buildingIndex = this.buildingIndex;
			buildingModel.buildingType = this.buildingType;
			buildingModel.height = this.height;
			buildingModel.population = this.population;
			buildingModel.roofType = this.roofType;
			buildingModel.sectionIndex = this.sectionIndex;
			buildingModel.posX = this.posX;
			buildingModel.posY = this.posY;
			buildingModel.ownerId = this.ownerId;
			buildingModel.isoWidth = this.isoWidth;
			buildingModel.isoHeight = this.isoHeight;
			buildingModel.rentCollectTime = this.rentCollectTime;
			buildingModel.stealRentCount = this.stealRentCount;
			buildingModel.lastRentClickTime = this.lastRentClickTime;
			buildingModel.locatedFlag = this.locatedFlag;
			return buildingModel;
		}
		
		public override function loadbyObject(object:Object):void
		{
			super.loadbyObject(object);
			var buildingConfig:BuildingConfig = Config.buildingConfigs[this.buildingIndex];
			isoHeight = buildingConfig.isoHeight > 0 ? buildingConfig.isoHeight : 1;
			isoWidth = buildingConfig.isoWidth > 0 ? buildingConfig.isoWidth : 1;
			socialInfos = new Array();
			socialMessageRead = true;
			if (object["socialInfo"] != null)
			{
				for (var str:String in object["socialInfo"])
				{			
					var socailModel:SocialModel = new SocialModel();
					socailModel.loadbyObject(object["socialInfo"][str]);
					if (socailModel.viewed == false && socialMessageRead == true)
					{
						socialMessageRead = false;
					}
					socialInfos.push(socailModel);
				}
			}
		}
		
		//收租
		public function collectRent(force:Boolean = false):void
		{
			var buildingConfig:BuildingConfig = Config.buildingConfigs[this.buildingIndex];
			var rentCollectCoolDown:int = buildingConfig.rentCollectCoolDown * 60;
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.COLLECT_RENT, {buildingId:id, rentCollectCoolDown: rentCollectCoolDown,
				rentObjectIndex: buildingConfig.rentObjectIndex});
			serverRequest.setHandleFunc(handleCollectRent);
			serverRequest.post(force);
			lastRentClickTime = ServerRequest.currentSeconds();
		}
		
		private function handleCollectRent(data:Object):void
		{
			var modelEvent:ModelEvent = new ModelEvent(ModelEvent.COLLECT_RENT_COMPLETE);
			modelEvent.data = data;
			//收租成功
			if (data["err"] == 0)
			{
				//更新收租时间
				if (data["rentCollectTime"] > 0)
					rentCollectTime = data["rentCollectTime"];
				//更新包裹
				var me:Player = PlayerManager.getInstance().me;
				var objects:Object = data['package']['objects'];
				me.packageModel.objectList = new Object();
				for (var s:String in objects)
				{
					var obj:Obj = new Obj();
					obj.loadbyObject(objects[s]);
					me.packageModel.objectList[s] = obj;
				}
			}
			dispatchEvent(modelEvent);
		}
		
		//保护作用剩余时间
		public function remainTimeToStopProtect():int
		{
			var owner:Player = PlayerManager.getInstance().players[ownerId];
			if (owner != null)
			{
				var stateList:Array = owner.stateModel.stateList;
				for (var i:int = 0; i < stateList.length; i++)
				{
					var stateInfo:StateInfo = stateList[i];
					if (stateInfo.state == StateConfig.PROTECT && stateInfo.sectionIndex == this.sectionIndex)
					{
						 var remainSeconds:int = stateInfo.deadline - ServerRequest.currentSeconds();
						return remainSeconds > 0 ? remainSeconds : 0;
					}
				}
			}
			return 0;
		}
		
		//查封解除剩余时间
		public function remainTimeToStopSeal():int
		{
			var owner:Player = PlayerManager.getInstance().players[ownerId];
			if (owner != null)
			{
				var stateList:Array = owner.stateModel.stateList;
				for (var i:int = 0; i < stateList.length; i++)
				{
					var stateInfo:StateInfo = stateList[i];
					if (stateInfo.state == StateConfig.SEAL && stateInfo.buildingId == this.id)
					{
						 var remainSeconds:int = stateInfo.deadline - ServerRequest.currentSeconds();
						return remainSeconds > 0 ? remainSeconds : 0;
					}
				}
			}
			return 0;
		}
		
		//是否能被收租
		public function isReadyToCollectRent():Boolean
		{
			var buildingConfig:BuildingConfig = Config.buildingConfigs[buildingIndex];
			if (buildingConfig.type == BuildingConfig.NORMAL)
			{
				//收租时间未到
				if (remainTimeToCollectRent() > 0)
					return false;
				var me:Player = PlayerManager.getInstance().me;
				//我占领的建筑
				if (this.occupantId == me.userId)
				{
					return true;
				}
				//别人占领的建筑
				else
				{
					var owner:Player = PlayerManager.getInstance().players[ownerId];
					if (owner == null || owner.type != PlayerManager.CENTER_TYPE && this.stealRentCount > 2)
						return false;
					else if (ServerRequest.currentSeconds() < lastRentClickTime + 300)
						return false
					else
						return true;
				}
			}
			return false;
		}
		
		public function remainTimeToCollectRent():int
		{
			var buildingConfig:BuildingConfig = Config.buildingConfigs[this.buildingIndex]; 
			var remainTime:int = rentCollectTime + buildingConfig.rentCollectCoolDown * 60 - ServerRequest.currentSeconds();
			remainTime = remainTime > 0 ? remainTime : 0;
			return remainTime;
		}
		
		public function getPts():Array
		{
			var array:Array = new Array();
			for (var i:int = 0; i< isoWidth ; i++)
			{
				for (var j:int = 0; j<isoHeight; j++)
				{
					array.push(new Point(posX + i, posY + j));
				}
			}
			return array;
		}
		
		//获取建筑物的自身信息
		public function getSocialInfo(buildingId:int):void
		{
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.GET_SOCIAL_INFO_OF_BUILDING, {buildingId:buildingId});
			serverRequest.setHandleFunc(handleGetSocialInfo);
			serverRequest.post();
		}

		//处理返回
		private function handleGetSocialInfo(data:Object):void
		{
			var event:ModelEvent = new ModelEvent(ModelEvent.GET_SOCIAL_INFO_OF_BUILDING);
			this.loadbyObject(data);
			//将事件的对象选择为发出事件的模型，
			dispatchEvent(event);
		}
	}
}